//
//  SQLMannger.swift
//  fmdbyanlian
//
//  Created by 李成万 on 16/7/8.
//  Copyright © 2016年 李成万. All rights reserved.
//

import UIKit
private let dbName = "status.db"
class SQLMannger {
    static let sharedTools:SQLMannger = SQLMannger()
    let queue : FMDatabaseQueue
    
    private init(){
        
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
        
        queue = FMDatabaseQueue(path: path)
        
        
        createTable()
    }
    
    private func createTable(){
        
        let file = NSBundle.mainBundle().pathForResource("db.sql", ofType: "")!
        let sql = try! String(contentsOfFile: file)
        
        queue.inDatabase { (db) -> Void in
            let result = db.executeStatements(sql)
            
            if result{
                print("创建表成功")
            }else{
                print("创建表失败")
            }
        }
     
    }
    
    func execRecord(sql:String) ->[[String:AnyObject]]{
        var tempArr:[[String:AnyObject]] = [[String:AnyObject]]()
        SQLMannger.sharedTools.queue.inDatabase { (db) -> Void in
            let result = db.executeQuery(sql, withArgumentsInArray: nil)
            var dict:[String:AnyObject] = [String:AnyObject]()
            
            while result.next(){
                for i in 0..<result.columnCount(){
                    let key = result.columnNameForIndex(i)
                    let value = result.objectForColumnIndex(i)
                    
                    dict[key] = value
                }
                tempArr.append(dict)
            }
        }
      return tempArr
    }
}
